/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.wxrobot.web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zhouyafeng.itchat4j.gui.PersonalFissionGUI;
import com.jeesite.common.codec.DesUtils;
import com.jeesite.common.codec.Md5Utils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.SpringUtils;
import com.jeesite.modules.sys.entity.Role;
import com.jeesite.modules.sys.entity.UserRole;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.wxrobot.ActivityConstants;
import com.jeesite.modules.wxrobot.entity.Customer;
import com.jeesite.modules.wxrobot.service.CustomerService;
import com.jeesite.modules.wxrobot.socketHandle.QrCodeWebSocketHandler;
import com.jeesite.modules.wxrobot.socketHandle.WebSocketConfig;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.wxrobot.entity.TaskActivity;
import com.jeesite.modules.wxrobot.service.TaskActivityService;

import java.util.List;
import java.util.Map;

/**
 * 任务宝活动Controller
 * @author sam
 * @version 2018-08-08
 */
@Controller
@RequestMapping(value = "${adminPath}/wxrobot/taskActivity")
public class TaskActivityController extends BaseController {

	@Autowired
	private TaskActivityService taskActivityService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private ServletContext servletContext;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public TaskActivity get(String id, boolean isNewRecord) {
		return taskActivityService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("wxrobot:taskActivity:view")
	@RequestMapping(value = {"list", ""})
	public String list(TaskActivity taskActivity, Model model) {
		model.addAttribute("taskActivity", taskActivity);
		return "modules/wxrobot/taskActivityList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("wxrobot:taskActivity:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<TaskActivity> listData(TaskActivity taskActivity, HttpServletRequest request, HttpServletResponse response) {
		taskActivity.setUserCode(UserUtils.getUser().getUserCode());
		Page<TaskActivity> page = taskActivityService.findPage(new Page<TaskActivity>(request, response), taskActivity);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("wxrobot:taskActivity:view")
	@RequestMapping(value = "form")
	public String form(TaskActivity taskActivity, Model model) {
		model.addAttribute("taskActivity", taskActivity);
		return "modules/wxrobot/taskActivityForm";
	}

	/**
	 * 保存任务宝活动
	 */
	@RequiresPermissions("wxrobot:taskActivity:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TaskActivity taskActivity) {
		taskActivity.setUserCode(UserUtils.getUser().getUserCode());
		//新增，默认状态为草稿
		if (taskActivity.getIsNewRecord()) {
			taskActivity.setStatus(String.valueOf(ActivityConstants.ActivityStatus.DRAFT.getCode()));
		}

		taskActivityService.save(taskActivity);
		return renderResult(Global.TRUE, text("保存任务宝活动成功！"));
	}
	
	/**
	 * 停用任务宝活动
	 */
	@RequiresPermissions("wxrobot:taskActivity:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(TaskActivity taskActivity) {
		taskActivity.setStatus(String.valueOf(ActivityConstants.ActivityStatus.OFFLINE.getCode()));
		taskActivityService.updateStatus(taskActivity);
		return renderResult(Global.TRUE, text("停用任务宝活动成功"));
	}
	
	/**
	 * 启用任务宝活动
	 */
	@RequiresPermissions("wxrobot:taskActivity:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(TaskActivity taskActivity) {
		/*
		否则生成机器人专属码、机器人海报供下载，插入机器人信息到客户表
		 */

		String realPath = servletContext.getRealPath("/");
		TaskActivity actConfig = taskActivityService.get(taskActivity);
		//生成固定长度的邀请码，前缀+0001
		StringBuilder selfCode = new StringBuilder(actConfig.getPrefixCode());
		selfCode.append("0001");
		//生成机器人海报
		logger.info("生成机器人海报activityId：{}，selfCode：{}", taskActivity.getId(), selfCode);
		Map<String, String> selfPoster = customerService.generateExclusivePoster(taskActivity.getId(), selfCode.toString(), realPath);
		String exclusivePosterPath = selfPoster.get("exclusivePosterContextPath");

		Customer cusCond = new Customer();
		cusCond.setActivityId(taskActivity.getId());
		cusCond.setRobot(1);
		List<Customer> customers = customerService.findList(cusCond);
		//不存在机器人客户，插入机器人客户
		if (customers == null || customers.size() == 0){

			//插入机器人信息到客户表
			Customer ins = new Customer();
			ins.setActivityId(taskActivity.getId());
			ins.setNickName("机器人");
			ins.setRobot(1);
			ins.setSubNum(0L);
			ins.setSelfCode(selfCode.toString());
			customerService.save(ins);
		}

		PersonalFissionGUI.start(taskActivity.getId(),UserUtils.getUser().getUserCode(), realPath);
		//更新活动状态为运行中
		taskActivity.setStatus(ActivityConstants.ActivityStatus.ONLINE.getCode()+"");
		taskActivity.setRobotPoster(exclusivePosterPath);
		//activityService.updateStatus(activity);
		taskActivityService.updateStatusAndRobotPoster(taskActivity);

		QrCodeWebSocketHandler qrCodeWebSocketHandler = (QrCodeWebSocketHandler)SpringUtils.getBean(WebSocketConfig.class).myHandler();
		qrCodeWebSocketHandler.sendQrCode(UserUtils.getUser().getUserCode(),"startSuccess");
		return renderResult(Global.TRUE, text("启用任务宝活动成功"));
	}
	
	/**
	 * 删除任务宝活动
	 */
	@RequiresPermissions("wxrobot:taskActivity:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TaskActivity taskActivity) {
		taskActivityService.delete(taskActivity);
		return renderResult(Global.TRUE, text("删除任务宝活动成功！"));
	}
	
}